<?php
/**
 * 控制初始和公用
 */
namespace APP\C;

use SF;



abstract class Controller
{
	const SESS_ADMIN = 'admin_name';

	// 模板
	public $view = null;

	// 请求
    public $request = null;

	// 路由
    public $router = null;

    // 数据库
    public $db = null;


    public function __construct()
    {
        // 获取request
        if (null === $this->request) {
        	$this->request = SF\Request::getInstance();
        }
    	// 获取路由
    	if (null === $this->router) {
    		$this->router = SF\Router::getInstance();
    	}
		// 获取view
    	if (null === $this->view) {
    		$this->view = SF\View\View::getInstance();
    	}
        // 获取数据库
        if (null === $this->db) {
            $this->db = $this->getDb();
        }

        // 权限验证
        if ($this->router->getController() != 'login' && !\SF\Session\Session::get(self::SESS_ADMIN)) {
            $this->router->redirect('/login');
        }

        // 模板路径
    	$this->view->setViewPath(APP_PATH .'/views');
    	// 缓存路径
    	$this->view->setCachePath(APP_PATH .'/tmp/views_c');
    	// Url根路径
    	$this->view->root = $baseUrl = $this->request->getBaseUrl();

        // 定义css和js路径
        $this->view->skin = $baseUrl .'/skin';
        $this->view->js = $baseUrl .'/js';
        $this->view->images = $baseUrl .'/images';

		$this->init();
    }

	protected function init()
	{
	}

	public function getDb()
	{
		if (!SF\Registry::isRegistered('db')) {
			SF\Registry::set('db', new SF\Db\Db(SF\Config::get('db')));
		}
		return SF\Registry::get('db');
	}
}